package com.sun.springbootelasticsearch.util;

import com.sun.springbootelasticsearch.bean.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HtmlParse {

    public static void main(String[] args) throws IOException {
       new HtmlParse().parseJD("java").forEach(System.out::println);
    }


    public List<Content> parseJD(String keyword) throws IOException {
        String url = "https://search.jd.com/Search?keyword=" + keyword;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");

        List<Content> contentList = new ArrayList<>();
        Elements elements = element.getElementsByTag("li");
        for (Element element1 : elements) {
            String img = element1.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = element1.getElementsByClass("p-price").eq(0).text();
            String name = element1.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setImg(img).setPrice(price).setTitle(name);
            contentList.add(content);
        }

        return contentList;
    }
}
